export enum STORAGE_KEY {
  CURRENT_USER = 'currentUser',
  INVITATION_CODE = 'invitation_code',
  EVERY_DAY_SIGN_IN = 'every_day_sign_in',
  MOTION_COUNT = 'motion_count'
}

type SetStorage<T> = (value: T) => void;

type StorageHook<STATE = any, SetStorageValue = any> = [STATE, SetStorage<SetStorageValue>];

type STATE_VALUE<T> = {
  value: T | null;
};

export const useStorage = <STATE = any>(key: STORAGE_KEY): StorageHook<STATE_VALUE<STATE>, STATE> => {
  const state: STATE_VALUE<STATE> = {
    value: (uni.getStorageSync(key) || null) as STATE
  };
  return [
    state,
    (value) => {
      if (state.value && typeof state.value === 'object' && typeof value === 'object' && !Array.isArray(value)) {
        Object.assign(state.value, value);
      } else {
        state.value = value;
      }
      uni.setStorageSync(key, value);
    }
  ];
};
